#include <iostream>
#include <string>


#include "grpcpp/grpcpp.h"
#include "greeter.grpc.pb.h"

class ServiceImpl final : public Greeter::Service {
    /**
     *! @brief 实现proto文件中定义的sayHello服务端函数逻辑
     * 
     * @param context  gPRC上下文，可能携带额外信息
     * @param request  自定义的请求信息
     * @param response 自定义的响应信息
     * 
     * @return ::grpc::Status  grpc状态码
     */
    virtual ::grpc::Status sayHello(::grpc::ServerContext *context,
                                const ::Request *request,
                                ::Response *response) {
        std::cout << "Name: " << request->name() 
            << ", Age: " << request->age() << std::endl;

        std::string message = "Name: " + request->name() 
                            + ", Age: " + std::to_string(request->age()) 
                            + "\n";

        response->set_message(message);

        return grpc::Status::OK;
    }
};


void start() {
    // 1. 设置服务程序参数
    // #include "grpcpp/grpcpp.h"
    grpc::ServerBuilder builder;

    // bind
    builder.AddListeningPort("0.0.0.0:5555",                   // 箭筒IP与端口
                            grpc::InsecureServerCredentials()  // 允许非安全链接
                        );

    ServiceImpl greeterSvc;
    builder.RegisterService(&greeterSvc);                      // 注册自定义服务对象


    // 2. 启动服务器
    // listen
    std::unique_ptr<grpc::Server> server = builder.BuildAndStart();

    server->Wait();
}


int main(int argc, char* argv[]) {

    start();

    return 0;
}